
module Hexena.Configuration ( getPath
                            , tryLoad
                            ) where

import Control.Exception
import Control.Monad (guard)
import System.IO.Error
import System.Posix.Files (getFileStatus)

tryLoad :: String -> IO String
tryLoad fn = f paths
    where f [] = error "list of paths ran try while trying to load file"
          f (x:xs) = do r <- tryJust (guard . isDoesNotExistError) $ readFile $ x ++ "/" ++ fn
                        case r of
                          Left  _   -> f xs
                          Right dat -> return dat

getPath :: String -> IO String
getPath fn = f $ map (\x -> x ++ "/" ++ fn) paths
    where f [] = error "list of paths ran try while trying to stat file"
          f (x:xs) = do r <- tryJust (guard . isDoesNotExistError) $ getFileStatus x
                        case r of
                          Left  _ -> f xs
                          Right _ -> return x


paths :: [String]
paths = [ ".", "./share", "/usr/local/share/hexena", "/usr/share/hexena" ]

